import uuid
from typing import Optional

from fastapi import APIRouter, Body, HTTPException
from pydantic import BaseModel, Field, ValidationError

from app.core.chains import get_introduction_practice_chain
from app.core.memory.memory_manager import get_session_history

router = APIRouter()


class Request(BaseModel):
    voiceString: str = Field(..., description="User's question for the knowledge base.")

class Response(BaseModel):
    processed_text: str


@router.post("/", response_model=Response)
def knowledge_base_chat(request_data: dict = Body(...)):
    """
    Handles a stateful chat request against the knowledge base.
    Uses conversation_id to maintain context.
    """
    try:
        # 手动验证请求数据
        print(f"收到的请求数据: {request_data}")
        request = Request(**request_data)
        print(f"收到的请求数据: {request_data}")
    except ValidationError as e:
        # 打印详细的验证错误
        print(f"请求数据验证失败: {e.errors()}")
        print(f"收到的请求数据: {request_data}")
        raise HTTPException(status_code=422, detail=e.errors())
    # position_list=["软件工程师","软件测试员"]
    # conv_id = request.conversation_id or str(uuid.uuid4())
    # print(f"--- KB Chat endpoint called for conversation_id: {conv_id} ---")
    # # 获取用户应聘岗位
    # position_id = request.position_id or str(uuid.uuid4())
    # position = position_list[position_id]
    # print(f"用户应聘岗位为：{position}")
    # chat_history_backend = get_session_history(conv_id)
    # introduction_practice_chain = get_introduction_practice_chain()

    # 从数据库获取岗位信息
    # try:
    #     position = db.execute(
    #         select(Position).where(Position.id == request.position_id)
    #     ).scalar_one_or_none()
    #
    #     if not position:
    #         raise HTTPException(
    #             status_code=404,
    #             detail=f"Position with ID {request.position_id} not found"
    #         )
    #
    #     position_name = position.name
    #     position_description = position.description or "No additional description"
    #     print(f"Found position: {position_name}")
    # except Exception as e:
    #     print(f"Database error: {str(e)}")
    #     raise HTTPException(
    #         status_code=500,
    #         detail="Failed to retrieve position information"
    #     )
    #
    # enhanced_query = (
    #     f"用户应聘的岗位为: {position}\n"
    #     f"用户输入的自我介绍为: {request.self_intro}\n"
    # )
    # print('enhanced_query:', enhanced_query)
    #
    #
    # result = introduction_practice_chain.invoke({
    #     "input": enhanced_query,
    #     "chat_history": chat_history_backend.messages
    # })
    #
    # answer = result.get("answer", "I'm sorry, I couldn't find an answer.")
    # print(f"{answer}")
    # chat_history_backend.add_user_message(enhanced_query)
    # chat_history_backend.add_ai_message(answer)

    return Response(
        processed_text='连接完成',
    )

